import axios from 'axios';
import qs from 'qs';
import Cookies from 'js-cookie';


import Vue from 'vue';
import { Dialog } from 'vant';
import { Toast } from 'vant';
Vue.use(Dialog);
Vue.use(Toast);

// axios.defaults.withCredentials = true;

// 请求拦截器
axios.interceptors.request.use(
  (request) => {
	
	  console.log(Cookies.get('token'));
    if (Cookies.get('token')) {
		let token = 'Bearer '+Cookies.get('token');
		
		
		// console.log(token,'-=====-0' , request.headers.common['Authorization'])
		
		// request.headers.common['Authorization'] = token;
		request.headers['Authorization'] = token;

		
		
	}
	if(request.method==='get'){
		request.data={unused:0};
		request.headers['Content-type']='application/json;charset=UTF-8';
	}
	// Toast.loading({
	// 	message: '生成结果中...',
	// 	forbidClick: true,
	// 	duration: 0
	// });
    return request;
  },
  (error) => {
	return Promise.reject(error);
  }
);

// 响应拦截器
axios.interceptors.response.use(
  (response) => {
	console.log(response)
	
	  console.log(response.status);
	  Toast.clear();
	  
	  if(response.status==401){
		  Dialog.confirm({
		    message: '无效的用户凭证或已过期，请重新登录',
		  	  confirmButtonText:'退出重试',
		  	  confirmButtonColor:'#4174F7'
		  }).then(() => {
		    // on confirm
		  		let ua = navigator.userAgent.toLowerCase();
		  		if (/iphone|ipad|ipod|macintosh/.test(ua)) {
		  			window.webkit.messageHandlers.gotoLastPage.postMessage(
		  				[JSON.stringify({ aa: 22 })]
		  			);
		  		} else if (/android/.test(ua)) {
		  			//android
		  			window.JSbridge.goBack();
		  		}
		  }).catch(() => {
		    // on cancel
		  });
		  return;
	  }else if (response.status !== 200) {
		return Promise.reject(new Error('状态码异常'));
	  }

    return response;
  },
  (error) => {
	  console.log('拦截器响应失败');
	  console.log(error);
	  console.log('-==================-------')
	  
	  Toast.clear();
	  if(error.code=='ECONNABORTED'){
		  Toast('服务器请求连接超时，请重试');
		  return;
	  }
	  // if(error.request){
	  // 	console.log(error.request);
	  // } else if(error.response){
	  // 	console.log(error.response.data);
	  // 	console.log(error.response.status);
	  // }
	  if (error && error.response) {
	  	switch (error.response.status) {
	  		case 400: Toast('请求错误(400)'); 
	  			break;
	  		case 401: 
				Dialog.confirm({
				  title: '退出提示',
				  message: '您的账号在另一台设备上登录，如非本人操作，则密码可能泄露，建议您重新登录后修改密码，点击“我的-系统设置-修改密码”进行修改',
				  confirmButtonText:'重新登录',
				  confirmButtonColor:'#4174F7'
				}).then(() => {
				  // on confirm
						let ua = navigator.userAgent.toLowerCase();
						if (/iphone|ipad|ipod|macintosh/.test(ua)) {
							window.webkit.messageHandlers.gotoLastPage.postMessage(
								[JSON.stringify({ aa: 22 })]
							);
						} else if (/android/.test(ua)) {
							//android
							window.JSbridge.goBack();
						}
				}).catch(() => {
				  // on cancel
				});
	  			break;
	  		case 403: Toast('拒绝访问(403)');
	  			break;
	  		case 404: Toast('请求出错(404)'); 
	  			break;
	  		case 408: Toast('请求超时(408)');
	  			break;
	  		case 500: Toast('服务器错误(500)');
	  			break;
	  		case 501: Toast('服务未实现(501)'); 
	  			break;
	  		case 502: Toast('网络错误(502)'); 
	  			break;
	  		case 503: Toast('服务不可用(503)'); 
	  			break;
	  		case 504: Toast('网络超时(504)'); 
	  			break;
	  		case 505: Toast('HTTP版本不受支持(505)');
	  			break;
	  		default: Toast('连接错误('+error.response.status+')');
	  	}
	  }else{
	  	error.message ='连接服务器失败!';
	  }
  }
);

/**
 * 这是一个请求方法
 * @param  {string}  method 请求方式
 * @param  {string}  url    请求连接
 * @param  {object}  obj    请求参数
 * @return {Promise}        返回 Promise
 */
export default function reqMethod(method, url, obj) {
  const modeKey = ['post'].includes(method.toLowerCase()) ? 'data' : 'params';
  const params = {
    url,
    timeout: 20000,
  };
  if (['post'].includes(method.toLowerCase())) {
    params.headers = {
      'X-Requested-With': 'XMLHttpRequest',
      'Content-Type': 'application/x-www-form-urlencoded',
    };
    params.method = method.toLowerCase();
    params[modeKey] = qs.stringify(obj || {}, { allowDots: true });
  } else if (['post_json'].includes(method.toLowerCase())) {
    params.headers = {
      'X-Requested-With': 'XMLHttpRequest',
      'Content-Type': 'application/json;charset=UTF-8',
    };
    params.method = 'post';
    params.data = JSON.stringify(obj);
  } else if (['post_file'].includes(method.toLowerCase())) {
    params.headers = {
      'X-Requested-With': 'XMLHttpRequest',
      'Content-Type': 'multipart/form-data',
    };
    params.method = 'post';
    params.data = obj;
  } else {
    params.method = method.toLowerCase();
    params[modeKey] = obj;
	params.headers = {
		'Content-Type': 'application/json;charset=UTF-8'
	};
	console.log(params);
  }
  return new Promise((resolve, reject) => {
    axios(params)
      .then((response) => {
        resolve(response.data, url);
        return response.data;
      })
      .catch((error) => {
        reject(error);
        return error;
      });
  });
}
